/**
 * @brief 自动获取本机IP
 * @note 不通用，在一些功能比较简陋的嵌入式linux系统上会失败，Could not connect
 */

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <iostream>
#include <string.h>

void GetLocalIp(void)
{
  	int sock = socket(PF_INET, SOCK_DGRAM, 0);
  	sockaddr_in loopback;

	if (sock == -1) {
		std::cout << "Could not socket";
		return ;
	}

	socklen_t addrlen = sizeof(loopback);
	memset(&loopback, 0, sizeof(loopback));
	loopback.sin_family = AF_INET;
	loopback.sin_addr.s_addr = inet_addr("1.1.1.1");
	loopback.sin_port = htons(53);

	if (connect(sock, reinterpret_cast<sockaddr *>(&loopback), sizeof(loopback)) == -1) 
	{
		std::cout << "Could not connect";
		close(sock);
		return ;
	}

	if (getsockname(sock, reinterpret_cast<sockaddr *>(&loopback), &addrlen) == -1) {
		std::cout << "Could not getsockname";
		close(sock);
		return;
	}

	char* pbuf = inet_ntoa(loopback.sin_addr);
	std::cout<< pbuf << std::endl;

	close(sock);
}
 
int main()
{
	GetLocalIp();
}